﻿/*
Copyright © 2011 Nokia Corporation. All rights reserved.
Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
Java and all Java-based marks are trademarks or registered trademarks of 
Sun Microsystems, Inc. Other product and company names mentioned herein may be 
trademarks or trade names of their respective owners.

Subject to the conditions below, you may, without charge:

·  Use, copy, modify and/or merge copies of this software and 
   associated content and documentation files (the “Software”)

·  Publish, distribute, sub-licence and/or sell new software 
   derived from or incorporating the Software.

Some of the documentation, content and/or software maybe licensed under open source software or other licenses.  To the extent such documentation, content and/or software are included, licenses and/or other terms and conditions shall apply in addition and/or instead of this notice. The exact terms of the licenses, disclaimers, acknowledgements and notices are reproduced in the materials provided.

This file, unmodified, shall be included with all copies or substantial portions
of the Software that are distributed in source code form.

The Software cannot constitute the primary value of any new software derived 
from or incorporating the Software.

Any person dealing with the Software shall not misrepresent the source of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

using System.Threading;
using System.ComponentModel;
using System.Device.Location;
using Microsoft.Phone.Controls.Maps;

namespace Carpool
{
    public partial class MyTrips : UserControl, KarpoDialog
    {
        private ObservableCollection<String> mytrips = null;
        private DCMyTripList dcmytriplist = null;

        private string followedcarpoolkarpoid = "";
        private int waitms = 10000;
        private bool activationfetchdone = true;
        private bool centerdrivericon = false;
        private double lastDriverLat = 0;
        private double lastDriverLon = 0;
        private BackgroundWorker bw = new BackgroundWorker();

        private bool simulationmode = false;
        private int simulationpolylineindex = 0;

        public MyTrips()
        {
            InitializeComponent();
            mytrips = new ObservableCollection<String>();
            mytripsCombo.DataContext = mytrips;

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);

        }

        public void showDialog(bool show)
        {
            MyTripsGrid.Visibility = Visibility.Visible;

            KarpoMessageBox.showMessageBox("Loading the trips...");
            dcmytriplist = new DCMyTripList(MainPage.userkarpoid);
            DC.DataCloud().GetMyTrips(dcmytriplist, getmytripscb);

        }


        internal void getmytripscb(bool isok, string errormsg, DCMyTripList dcmytrips)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dcmytrips.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dcmytrips.errorString);
            }
            else
            {
                dcmytriplist = dcmytrips;

                mytrips.Clear();
                for (int i = 0; i < dcmytriplist.mytriplist.Count(); i++)
                {
                    String routename = dcmytriplist.mytriplist[i].routename;
                    if (dcmytriplist.mytriplist[i].active == "1")
                    {
                        routename += " [A]";
                    }

                    mytrips.Add(routename);
                }

                if (dcmytriplist.mytriplist.Count() > 0)
                {
                    mytripsCombo.SelectedIndex = 0;
                }
                KarpoMessageBox.hideMessageBox();

            }
        }

        public void menuCommand(string command)
        {
            if (command == "Back...")
            {
                followedcarpoolkarpoid = "";
                lastDriverLat = 0;
                lastDriverLon = 0;
                centerdrivericon = false;
                simulationmode = false;
                MainPage.main.resetMenu();
                MainPage.main.routetool.clearMapObjects();
                MyTripsGrid.Visibility = Visibility.Collapsed;
            }
            else if (command == "Locate")
            {
                if (lastDriverLat > 0 && lastDriverLon > 0)
                {
                    MainPage.main.routetool.centerMapToCoordinates(lastDriverLat, lastDriverLon);
                }
            }
            else if (command == "Locating OFF")
            {
                centerdrivericon = false;
                MainPage.appcase = "following";
            }
            else if (command == "Locating ON")
            {
                centerdrivericon = true;
                MainPage.appcase = "following_locating_on";
            }
            else if (command == "Stop following")
            {
                if (simulationmode)
                {
                    simulationmode = false;
                    MainPage.appcasesub = "";
                    saveSimulationOff();
                }  

                bw.CancelAsync();
                followedcarpoolkarpoid = "";
                lastDriverLat = 0;
                lastDriverLon = 0;
                centerdrivericon = false;

                MainPage.main.resetMenu();
                MainPage.main.routetool.clearMapObjects();
            }
            else if (command == "Simulation ON")
            {
                MainPage.appcasesub = "simulation_is_on";
                simulationpolylineindex = -1;
                simulationmode = true;
            }
            else if (command == "Simulation OFF")
            {
                MainPage.appcasesub = "";
                simulationmode = false;
                saveSimulationOff();

                MainPage.main.routetool.showDriverPin(lastDriverLat, lastDriverLon, centerdrivericon, "");
            }
        }

        public void crosshairLocation(double lat, double lon)
        {

        }

        private void MyTripsGrid_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            mytripsTranslateTransform.X += e.DeltaManipulation.Translation.X;
            mytripsTranslateTransform.Y += e.DeltaManipulation.Translation.Y;
        }


        private bool showRoute(int ind)
        {
            if (ind > -1 && ind < dcmytriplist.mytriplist.Length)
            {
   
                MainPage.main.routetool.fromRoute = new DCRoutePoint();
                MainPage.main.routetool.fromRoute.type = "FROMPOINT";
                MainPage.main.routetool.fromRoute.pointset = true;
                MainPage.main.routetool.fromRoute.routepolyline = "[]";
                MainPage.main.routetool.fromRoute.latitude = Double.Parse(dcmytriplist.mytriplist[ind].routefromlat);
                MainPage.main.routetool.fromRoute.longitude = Double.Parse(dcmytriplist.mytriplist[ind].routefromlon);
                MainPage.main.routetool.fromRoute.street = dcmytriplist.mytriplist[ind].routefromstreet;
                MainPage.main.routetool.fromRoute.city = dcmytriplist.mytriplist[ind].routefromcity;
                MainPage.main.routetool.fromRoute.postcode =dcmytriplist.mytriplist[ind].routefrompostcode;
                MainPage.main.routetool.fromRoute.country = dcmytriplist.mytriplist[ind].routefromcountry;


                MainPage.main.routetool.toRoute = new DCRoutePoint();
                MainPage.main.routetool.toRoute.type = "TOPOINT";
                MainPage.main.routetool.toRoute.pointset = true;
                MainPage.main.routetool.toRoute.routepolyline = "[]";
                MainPage.main.routetool.toRoute.latitude = Double.Parse(dcmytriplist.mytriplist[ind].routetolat);
                MainPage.main.routetool.toRoute.longitude = Double.Parse(dcmytriplist.mytriplist[ind].routetolon);
                MainPage.main.routetool.toRoute.street = dcmytriplist.mytriplist[ind].routetostreet;
                MainPage.main.routetool.toRoute.city = dcmytriplist.mytriplist[ind].routetocity;
                MainPage.main.routetool.toRoute.postcode = dcmytriplist.mytriplist[ind].routetopostcode;
                MainPage.main.routetool.toRoute.country = dcmytriplist.mytriplist[ind].routetocountry;


                MainPage.main.routetool.routekarpoid = dcmytriplist.mytriplist[ind].routeindexkarpoid;
                MainPage.main.routetool.routecarpoolkarpoid = dcmytriplist.mytriplist[ind].carpoolkarpoid;
                MainPage.main.routetool.routekarponame = dcmytriplist.mytriplist[ind].routename;
                MainPage.main.routetool.routedescription = dcmytriplist.mytriplist[ind].routedescription;

                MainPage.main.routetool.routerepeat = dcmytriplist.mytriplist[ind].routerepeat;
                MainPage.main.routetool.routetime = dcmytriplist.mytriplist[ind].routetime;

                MainPage.main.routetool.routeshowuserphone = false;
                MainPage.main.routetool.routeshowusername = false;
                MainPage.main.routetool.routeshowuserhometown = false;

                MainPage.main.routetool.CalculateRouteLatLon(MainPage.main.routetool.fromRoute.latitude, MainPage.main.routetool.fromRoute.longitude,
                    MainPage.main.routetool.toRoute.latitude, MainPage.main.routetool.toRoute.longitude);



                return true;
            }
            else
            {
                KarpoMessageBox.showMessageBox("No selected trip to show!");
                return false;
            }
        }

        private void showbutton_Click(object sender, RoutedEventArgs e)
        {
            showRoute(mytripsCombo.SelectedIndex);
        }

        private void followbutton_Click(object sender, RoutedEventArgs e)
        {
            if (showRoute(mytripsCombo.SelectedIndex))
            {
                followedcarpoolkarpoid = dcmytriplist.mytriplist[mytripsCombo.SelectedIndex].carpoolkarpoid;

                MainPage.appcase = "following";
                MyTripsGrid.Visibility = Visibility.Collapsed;

                bw.RunWorkerAsync();

            }
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            bool dowork = true;
            activationfetchdone = true;
            waitms = 5000;
            while (dowork)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    dowork = false;
                }
                else
                {
                    if (followedcarpoolkarpoid.Length > 0 && activationfetchdone)
                    {
                        activationfetchdone = false;
                        waitms = 5000;
                        
                        // Simulation
                        if (simulationmode)
                        {
                            if (MainPage.main.routetool.routeModel != null)
                            {
                                simulationpolylineindex++;
                                if (simulationpolylineindex == MainPage.main.routetool.routeModel.Count)
                                {
                                    simulationpolylineindex = 0;
                                }
                                if (simulationpolylineindex < MainPage.main.routetool.routeModel.Count)
                                {
                                    GeoCoordinate gc = MainPage.main.routetool.routeModel.ElementAt(simulationpolylineindex);

                                    DCCarPoolActivationList dccarpoolactivationlist = new DCCarPoolActivationList();
                                    DCCarPoolActivation dccarpoolactivation = new DCCarPoolActivation(followedcarpoolkarpoid);
                                    dccarpoolactivation.lat = gc.Latitude.ToString();
                                    dccarpoolactivation.lon = gc.Longitude.ToString();
                                    dccarpoolactivation.alias = "SIMULATION";
                                    dccarpoolactivation.active = "1";

                                    dccarpoolactivationlist.carpoolactivationlist = new DCCarPoolActivation[] { dccarpoolactivation };
                                    DC.DataCloud().SetCarPoolActivation(dccarpoolactivationlist, carpoolactivationcb);
                                }
                            }
                        }
                        else
                        {
                            DCCarPoolActivationList carpoolactivationlist = new DCCarPoolActivationList();
                            carpoolactivationlist.carpoolactivationlist = new DCCarPoolActivation[1];
                            carpoolactivationlist.carpoolactivationlist[0] = new DCCarPoolActivation(followedcarpoolkarpoid);

                            DC.DataCloud().GetCarPoolActivation(carpoolactivationlist, carpoolactivationcb);
                        }                    
                    }
                    System.Threading.Thread.Sleep(waitms);                     
                }
            }
        }

        private void saveSimulationOff()
        {
 
            DCCarPoolActivationList dccarpoolactivationlist = new DCCarPoolActivationList();
            DCCarPoolActivation dccarpoolactivation = new DCCarPoolActivation(followedcarpoolkarpoid);
            dccarpoolactivation.lat = lastDriverLat.ToString();
            dccarpoolactivation.lon = lastDriverLon.ToString();
            dccarpoolactivation.alias = "";
            dccarpoolactivation.active = "0";

            dccarpoolactivationlist.carpoolactivationlist = new DCCarPoolActivation[] { dccarpoolactivation };
            DC.DataCloud().SetCarPoolActivation(dccarpoolactivationlist, carpoolactivationcb);
        }


        internal void carpoolactivationcb(bool isok, string errormsg, DCCarPoolActivationList dccarpoolactivationlist)
        {
            activationfetchdone = true;
            waitms = 1000;

            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccarpoolactivationlist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccarpoolactivationlist.errorString);
            }
            else if (dccarpoolactivationlist.carpoolactivationlist.Count() > 0)
            {
                DCCarPoolActivation dccarpoolactivation = dccarpoolactivationlist.carpoolactivationlist[0];
                if (dccarpoolactivation.active == "1" && dccarpoolactivation.lat != null && dccarpoolactivation.lat.Length > 0 && dccarpoolactivation.lon != null && dccarpoolactivation.lon.Length > 0)
                {
                    lastDriverLat = Double.Parse(dccarpoolactivation.lat);
                    lastDriverLon = Double.Parse(dccarpoolactivation.lon);

                    MainPage.main.routetool.showDriverPin(lastDriverLat, lastDriverLon, centerdrivericon, dccarpoolactivation.alias);

                }

            }
        }

        private void closebutton_Click(object sender, RoutedEventArgs e)
        {
            followedcarpoolkarpoid = "";
            lastDriverLat = 0;
            lastDriverLon = 0;
            centerdrivericon = false;
            MainPage.main.resetMenu();
            MainPage.main.routetool.clearMapObjects();
            MyTripsGrid.Visibility = Visibility.Collapsed;
        }

        private void unjoinbutton_Click(object sender, RoutedEventArgs e)
        {
            if (mytripsCombo.SelectedIndex > -1)
            {
                KarpoMessageBox.showMessageBox("Unjoining from the trip...");
                String unjoinmemberindexkarpoid = dcmytriplist.mytriplist[mytripsCombo.SelectedIndex].memberindexkarpoid;
                DCKarpoIdList dckarpoidlist = new DCKarpoIdList(MainPage.userkarpoid, MainPage.userpassword, MainPage.username);
                dckarpoidlist.karpoids = new string[1];
                dckarpoidlist.karpoids[0] = unjoinmemberindexkarpoid;
                DC.DataCloud().DeleteCarpoolMembers(dckarpoidlist, deletecarpoolmembercb);
                MainPage.main.routetool.clearMapObjects();

            }
            else
            {
                KarpoMessageBox.showMessageBox("No trip selected!");
            }
            
        }

        internal void deletecarpoolmembercb(bool isok, string errormsg, DCKarpoIdList dckarpoidlist)
        {

            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dckarpoidlist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dckarpoidlist.errorString);
            }
            else if (dckarpoidlist.karpoids.Count() > 0)
            {
               
                KarpoMessageBox.showMessageBox("Loading the trips again...");
                mytrips.Clear();
                dcmytriplist = new DCMyTripList(MainPage.userkarpoid);
                // wait 2 secs so that the datacloud has time to update
                System.Threading.Thread.Sleep(2000); 
                DC.DataCloud().GetMyTrips(dcmytriplist, getmytripscb);
                 
            }
        }
    }
}
